//   //字符串截取
function mul(arg1, arg2) {
  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();
  try {
    m += s1.split(".")[1].length
  } catch (e) { }
  try {
    m += s2.split(".")[1].length
  } catch (e) { }
  return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    wrapCategory: false,
    animationData: {},
    categoryNumber:[
      {
        categoryIndex:0,
        categoryText:"",
        weight:" ",
        price:" ",
        subTotal: 0.00,
        categoryId:""
        //allTotal: 0
      }
      ],
    listCategory: " ",//存放回收类别对象
    categorySelect: 0,//判断是否选中
    indexNumber:0,
    text:"",//用于存储回收类别列表值得变量
    id: "",//类别id
    weight:" ",
    allTotal: 0.00,
    buthidden:false,
    orderVo:{},//用于存储订单信息
    bId:"",//订单id
    wxType: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log((options.bId));
    var bId = options.bId;
    var that = this;
    that.setData({
      bId: bId,
      wxType: app.globalData.wxType
    });
    // console.log(that.data.text_category);
    wx.request({
      method: "POST",
      url: 'https://www.zaishengwang.com/wx/toHomePriced.do',
      dataType : 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        id: bId
      },
      success: function (res) {
        console.log(res.data.orderVo);
        let createTime = res.data.orderVo.createTime.substring(0,19);
        res.data.orderVo.createTime = createTime;
        that.setData({ orderVo: res.data.orderVo, listCategory: res.data.listCategory});
        
        var index = that.data.indexNumber;
        var categoryText = "categoryNumber[" + index + "].categoryText";
        var categoryId = "categoryNumber[" + index + "].categoryId";
        that.setData({
          [categoryText]: that.data.listCategory[0].name,
          [categoryId]: that.data.listCategory[0].categoryId,
        });
      },
      fail: function (error) {
        console.log(error);
      }

    })
    
  },
//显示弹窗事件
  wrapCategorySelect: function (e) {
    console.log(e);
    console.log(e.currentTarget.dataset.index);
    
    var that = this;
    that.data.indexNumber = e.currentTarget.dataset.index;

    // 创建一个动画实例
    var animation = wx.createAnimation({
      // 动画持续时间
      duration: 500,
      // 定义动画效果，当前是匀速
      timingFunction: 'linear'
    })
    // 将该变量赋值给当前动画
    that.animation = animation
    // 先在y轴偏移，然后用step()完成一个动画
    animation.translateY(200).step()
    // 用setData改变当前动画
    that.setData({
      // 通过export()方法导出数据
      animationData: animation.export(),
      // 改变view里面的Wx：if
      wrapCategory: true
    })
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export()
      })
    }, 200)
  },
//隐藏弹窗事件
  hideModal: function (e) {
    var that = this;
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'linear'
    })
    that.animation = animation
    animation.translateY(200).step()
    that.setData({
      animationData: animation.export()

    })
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export(),
        wrapCategory: false
      })
    }, 200)
  },
//底部弹层选择事件
  categoryList: function (e) {
    console.log(e)
    var that = this;
    that.setData({//把选中值放入判断值
      categorySelect: e.currentTarget.dataset.select,
      text: e.currentTarget.dataset.text,
      id: e.currentTarget.dataset.id
    })
    console.log(e.currentTarget.dataset.text)
  },
//确定事件
  sureBtn: function () {
    var that = this;
    var index = that.data.indexNumber;
    console.log(index);
    var categoryText = "categoryNumber[" + index + "].categoryText";
    var categoryId = "categoryNumber[" + index + "].categoryId";
    that.setData({
     [categoryText]:that.data.text,
     [categoryId]: that.data.id,
    });
    
    console.log(that.data.categoryNumber); 
  
    that.hideModal();

  },
// 添加回收物增加节点事件
  addNode:function(){
    var that = this;
    var i = 1;
    i++;

    that.setData({
      categoryNumber: that.data.categoryNumber.concat([
        {
        categoryIndex: i,
        categoryText: that.data.listCategory[0].name,
        weight: "",
        price: "",
        subTotal: 0.00,
        categoryId: that.data.listCategory[0].categoryId
        }
      ])
    });
    console.log(that.data.categoryNumber);
  },
  //浮点数计算
  allTotal: function () {
    var that = this;
    var arr_sub = that.data.categoryNumber;
    var str_sub = 0;
    for (var i = 0; i < arr_sub.length; i++) {
      str_sub = str_sub + parseFloat(arr_sub[i].subTotal);
    }
    return str_sub;
  },

  //录入重量
  onNumberWeight:function(e){
    var that = this;
    var index = e.currentTarget.dataset.index; 
    var weight = "categoryNumber[" + index + "].weight";
    var price = that.data.categoryNumber[index].price;
    var subTotal = "categoryNumber[" + index + "].subTotal";
    that.setData({ [weight]: e.detail.value.replace(/[^\d.]/g, "") });
    that.setData({ [weight]: e.detail.value.replace(/\.{2,}/g, ".") });
    that.setData({ [weight]: e.detail.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".") });
    that.setData({ [weight]: e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')});

    if (e.detail.value != "") {
      var weight = e.detail.value;
      var subTotalNow = mul(price, weight);
      

      that.setData({
        [weight]: weight,
        [subTotal]: subTotalNow,
      });
    }
    var allTotal_ = that.allTotal();
    that.setData({
      allTotal: allTotal_
    })
  },

  //录入单价
  onNumberPrice: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var price = "categoryNumber[" + index + "].price";
    var weight = that.data.categoryNumber[index].weight;
    var subTotal = "categoryNumber[" + index + "].subTotal";
    that.setData({ [price]: e.detail.value.replace(/[^\d.]/g, "") });
    that.setData({ [price]: e.detail.value.replace(/\.{2,}/g, ".") });
    that.setData({ [price]: e.detail.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".") });
    that.setData({ [price]: e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') });

    if (e.detail.value != "") {
      var num = (weight * e.detail.value).toFixed(2);
      that.setData({
        [price]: e.detail.value,
        [subTotal]: num,
      });
    }

    var allTotal_ = that.allTotal();
    that.setData({
      allTotal: allTotal_,
    })
  },

  bindFormSubmit:function(){
    var that = this; 
    var length = that.data.categoryNumber.length;
    var category = that.data.categoryNumber;
    var categoryStr = [];
    var actualWeightStr = [];
    var priceStr = [];
    var subTotalPriceStr = [];
    for (let i = 0; i < length; i++) {
      categoryStr.push(category[i].categoryId);
      actualWeightStr.push(category[i].weight);
      priceStr.push(category[i].price);
      subTotalPriceStr.push(category[i].subTotal);
    }

    var categoryStrLen = categoryStr.length;
    var actualWeightStrLen = actualWeightStr.length;
    var priceStrLen = priceStr.length;
    for (let i = 0; i < categoryStrLen; i++){
      if (!categoryStr[i] || categoryStr[i] == " " || categoryStr[i] =="undefind" ){
        wx.showToast({
          title: '回收类别不能为空',
          icon:'none'
        })

        return ;
      }
    }

    for (let i = 0; i < actualWeightStrLen; i++) {
      if (!actualWeightStr[i] || actualWeightStr[i] == " " || actualWeightStr[i] == "undefind") {
        wx.showToast({
          title: '重量不能为空',
          icon: 'none'
        })
        return ;
      }
    }

    for (let i = 0; i < priceStrLen; i++) {
      if (!priceStr[i] || priceStr[i] == " " || priceStr[i] == "undefind") {
        wx.showToast({
          title: '单价不能为空',
          icon: 'none' 
        })
        return ;
      }
    }
    that.setData({ buthidden: true });

    wx.request({
      method: "POST",
      url: 'https://www.zaishengwang.com/wx/toUpdateOrder.do?categoryStr[]=' + categoryStr + '&actualWeightStr[]=' + actualWeightStr + '&priceStr[]=' + priceStr,
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        id: that.data.bId,
        status:1
        //categoryStr: categoryStr,
        //actualWeightStr: actualWeightStr,
        //priceStr: priceStr
      },
      success: function (res) {
        console.log(res);
        if (res.data.msg == "1") {
          wx.navigateTo({
            url: 'payment?bId=' + that.data.bId + "&allTotal=" + that.data.allTotal
          })
        }else{
          that.setData({ buthidden: false });
        }
        
      },
      fail: function (error) {
        console.log(error);
        that.setData({ buthidden: false });
      }

    })

  },

  noScroll: function () {
    //微信小程序有bind和catch两种事件绑定方法，bind事件绑定不会阻止冒泡事件向上冒泡，catch事件绑定可以阻止冒泡事件向上冒泡。我们使用catch绑定手指触摸事件，然后他的父节点就不会收到事件冒泡，这样就实现了禁止页面上下滑动
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})